package com.lakala.sh.bps.bpsmerchant.client.utils;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 * 异步通知HTTP POST
 */
public class HttpPostUtil {

	private static final Logger logger = LoggerFactory.getLogger(HttpPostUtil.class);

	private static final int CONNECT_TIMEOUTMS = 3000;
	private static final int READ_TIMEOUTMS = 3000;

	/**
	 * 异步通知HTTP POST
	 *
	 * @param data
	 * @param url
	 * @return
	 */
	public static String dataPost(String data, String url) {
		logger.info(">>>异步通知url：{}-报文信息：{}", url, data);
		String resp = null;
		HttpURLConnection httpURLConnection = null;
		OutputStream outputStream = null;
		InputStream inputStream = null;
		BufferedReader bufferedReader = null;
		try {
			URL httpUrl = new URL(url);
			httpURLConnection = (HttpURLConnection) httpUrl.openConnection();
			httpURLConnection.setDoOutput(true);
			httpURLConnection.setRequestMethod("POST");
			// 设定请求格式json，也可以设定xml格式的
			httpURLConnection.setRequestProperty("Content-Type", "application/json");
			httpURLConnection.setConnectTimeout(CONNECT_TIMEOUTMS);
			httpURLConnection.setReadTimeout(READ_TIMEOUTMS);
			httpURLConnection.connect();

			outputStream = httpURLConnection.getOutputStream();
			outputStream.write(data.getBytes("UTF-8"));
			inputStream = httpURLConnection.getInputStream();
			bufferedReader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"));
			final StringBuffer stringBuffer = new StringBuffer();
			String line = null;
			while ((line = bufferedReader.readLine()) != null) {
				stringBuffer.append(line);
			}
			resp = stringBuffer.toString();
			logger.info(">>>异步通知url：{}-返回报文：{}", url, resp);
		} catch (Exception e) {
			logger.error(">>>url：{}-通知通讯异常：{}", url, e);
			throw new RuntimeException(e.getMessage(), e);
		} finally {
			if (bufferedReader != null) {
				try {
					bufferedReader.close();
				} catch (Exception e) {
					logger.error(">>>url：{}-bufferedReader：{}", url, e);
					throw new RuntimeException(e.getMessage(), e);
				}
			}
			if (inputStream != null) {
				try {
					inputStream.close();
				} catch (Exception e) {
					logger.error(">>>url：{}-inputStream：{}", url, e);
					throw new RuntimeException(e.getMessage(), e);
				}
			}
			if (outputStream != null) {
				try {
					outputStream.close();
				} catch (Exception e) {
					logger.error(">>>url：{}-outputStream：{}", url, e);
					throw new RuntimeException(e.getMessage(), e);
				}
			}
			if (httpURLConnection != null) {
				try {
					httpURLConnection.disconnect();
					httpURLConnection = null;
				} catch (Exception e) {
					logger.error(">>>url：{}-httpURLConnection：{}", url, e);
					throw new RuntimeException(e.getMessage(), e);
				}
			}
		}
		return resp;
	}
}
